package com.tanhua.sso.controller;

import com.tanhua.sso.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @Author YuShiLong
 * @Date 2021/4/12 18:58
 * @Version 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     *
     * @param param
     * @return
     */
    @PostMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {

        try {
            //从前端获取手机号码和验证码
            String phone = param.get("phone");
            String code = param.get("verificationCode");

            //调用业务层的login方法,把手机号和验证码作为参数传递过去,返回结果
            Map<String, Object> data = userService.login(phone, code);

            //如果data不为空代表有数据
            if (data != null) {
                //向前端返回数据
                return ResponseEntity.ok(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("000002").errMessage("登录失败!").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    /**
     * 校验token，根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserToken(@PathVariable("token") String token) {
        return this.userService.queryUserToken(token);
    }
}
